/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import binding.userdetails.UserDetails;
import binding.users.UserType;
import binding.users.Users;
import core.DBEntities;
import core.XmlChecker;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.Source;
import utils.CommonUtils;
import utils.XmlUtils;

public class UserController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, JAXBException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            String path = getServletContext().getContextPath();
            String webPath = getServletContext().getRealPath("/");
            String xmlUser = webPath + "WEB-INF/XmlDoc/Users.xml";
            String xmlUserDetail = webPath + "WEB-INF/XmlDoc/UserDetails.xml";
            String xsdUser = webPath + "WEB-INF/classes/schemas/users.xsd";
            String xslManagement = webPath + "WEB-INF/XslDoc/Management.xsl";

            if (action.equals("Login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                String page = request.getParameter("page");
                UserType ut = new UserType();
                ut = DBEntities.checkLogin(username, password);
                HttpSession session = request.getSession();
                if (ut != null) {
                    if (ut.isIsActive()) {
                        session.setAttribute("USER_ERROR", null);
                        session.setAttribute("USER_ROLE", ut.getRoleName());
                        session.setAttribute("USER_NAME", ut.getUsername());
                        session.setAttribute("USER_ID", ut.getId());
                        if (ut.getRoleName().equals("admin")) {
                            response.sendRedirect(path + "/management/Admin.jsp");
                        } else {
                             response.sendRedirect(path);
                        }
                    } else {
                        request.setAttribute("USER_ERROR", "Account đã bị khoá");
                        if (page != null) {
                            request.getRequestDispatcher("/" + page).forward(request, response);
                        }
                        request.getRequestDispatcher("/").forward(request, response);
                    }
                } else {
                    request.setAttribute("USER_ERROR", "Account/Password không đúng");
                    if (page != null) {
                        request.getRequestDispatcher("/" + page).forward(request, response);
                    }
                    request.getRequestDispatcher("/").forward(request, response);
                }
            } else if (action.equals("Logout")) {
                HttpSession session = request.getSession();
                session.setAttribute("USER_ROLE", null);
                session.setAttribute("USER_NAME", null);
                session.setAttribute("USER_ID", null);
                session.setAttribute("USER_RESTAURANTID", null);
                response.sendRedirect(path);
            } else if (action.equals("Check_UserName")) {
                String username = request.getParameter("username");
                boolean isDup = DBEntities.checkUsername(username);
                out.write(String.valueOf(isDup));
            } else if (action.equals("Add_Account")) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String email = request.getParameter("email");
                String firstName = request.getParameter("firstName");
                String lastName = request.getParameter("lastName");
                String province = request.getParameter("province");
                String district = request.getParameter("district");
                String address = request.getParameter("address");
                String phoneNum = request.getParameter("phoneNum");

                boolean isDone = false;
                isDone = DBEntities.createAccount(firstName, lastName, email, province, district,
                        address, phoneNum, username, password);
                if (isDone) {
                    if (XmlChecker.isExistFile(xmlUser) || XmlChecker.isExistFile(xmlUserDetail)) {
                        Users listusers = DBEntities.getListUser();
                        XmlUtils.marshalXml(listusers, xmlUser);
                        UserDetails listuserdetals = DBEntities.getListUserDetail();
                        XmlUtils.marshalXml(listuserdetals, xmlUserDetail);
                    }
                    out.write("Done");
                } else {
                    out.write("Has an error. Please check the database connection.");
                }
            } else if (action.equals("USER_ACTIVATION")) {
                String uid = request.getParameter("userid");
                Object obj = XmlUtils.unMarshalXml(xsdUser, xmlUser, Users.class);
                if (obj != null && obj instanceof Users) {
                    Users reslist = (Users) obj;
                    UserType resType = null;
                    for (UserType r : reslist.getUser()) {
                        if (uid.equals(String.valueOf(r.getId().intValue()))) {
                            resType = r;
                        }
                    }
                    if (resType != null) {
                        resType.setIsActive(!resType.isIsActive());
                    }
                    //save to db
                    if (DBEntities.saveUser(resType)) {
                        XmlUtils.marshalXml(reslist, xmlUser);
                        JAXBContext jc = JAXBContext.newInstance(Users.class);
                        Source jaxbSource = new JAXBSource(jc, obj);
                        Map<String, Object> params = new LinkedHashMap<String, Object>();
                        params.put("type", "containuser");
                        String sResponse = XmlUtils.transformToString(xslManagement, jaxbSource, params);
                        out.write(sResponse);
                    }
                }
            } else if (action.equals("USER_ROLE_UPDATE")) {
                String uid = request.getParameter("userid");
                String roleid = request.getParameter("roleid");
                Object obj = XmlUtils.unMarshalXml(xsdUser, xmlUser, Users.class);
                if (obj != null && obj instanceof Users) {
                    Users reslist = (Users) obj;
                    UserType uType = null;
                    for (UserType r : reslist.getUser()) {
                        if (uid.equals(String.valueOf(r.getId().intValue()))) {
                            uType = r;
                        }
                    }
                    if (uType != null) {
                        uType.setRoleId(BigInteger.valueOf(CommonUtils.convertStringToInt(roleid)));
                    }
                    //save to db
                    if (DBEntities.saveUser(uType)) {
                        XmlUtils.marshalXml(reslist, xmlUser);
                        JAXBContext jc = JAXBContext.newInstance(Users.class);
                        Source jaxbSource = new JAXBSource(jc, obj);
                        Map<String, Object> params = new LinkedHashMap<String, Object>();
                        params.put("type", "containuser");
                        String sResponse = XmlUtils.transformToString(xslManagement, jaxbSource, params);
                        out.write(sResponse);
                    }
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {

            processRequest(request, response);
        } catch (JAXBException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {

            processRequest(request, response);
        } catch (JAXBException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
